/**
 * 多端推送通知工具
 */
import platform from './platform.js'
import storage from './storage.js'

// 初始化推送
export const initPush = () => {
  return new Promise((resolve, reject) => {
    // #ifdef MP-WEIXIN
    // 微信小程序订阅消息
    uni.requestSubscribeMessage({
      tmplIds: [
        'template_id_1', // 新消息通知
        'template_id_2', // 点赞通知
        'template_id_3'  // 评论通知
      ],
      success: (res) => {
        console.log('订阅消息成功:', res)
        resolve(res)
      },
      fail: (err) => {
        console.log('订阅消息失败:', err)
        reject(err)
      }
    })
    // #endif
    
    // #ifdef H5
    // H5环境使用Web Push API
    if ('Notification' in window) {
      if (Notification.permission === 'granted') {
        resolve({ permission: 'granted' })
      } else if (Notification.permission !== 'denied') {
        Notification.requestPermission().then(permission => {
          resolve({ permission })
        }).catch(reject)
      } else {
        reject(new Error('通知权限被拒绝'))
      }
    } else {
      reject(new Error('浏览器不支持通知'))
    }
    // #endif
    
    // #ifdef APP-PLUS
    // APP环境使用个推或其他推送服务
    plus.push.createMessage('', 'UNI_MESSAGE', {
      cover: false
    })
    
    plus.push.addEventListener('click', (message) => {
      console.log('推送消息点击:', message)
      handlePushClick(message)
    })
    
    plus.push.addEventListener('receive', (message) => {
      console.log('收到推送消息:', message)
      handlePushReceive(message)
    })
    
    resolve({ status: 'initialized' })
    // #endif
  })
}

// 发送本地通知
export const sendLocalNotification = (options = {}) => {
  const {
    title = '新消息',
    content = '',
    icon = '/static/logo.png',
    sound = 'default',
    vibrate = true
  } = options
  
  // #ifdef MP-WEIXIN
  // 微信小程序暂不支持本地通知
  console.log('小程序不支持本地通知')
  // #endif
  
  // #ifdef H5
  if ('Notification' in window && Notification.permission === 'granted') {
    const notification = new Notification(title, {
      body: content,
      icon: icon,
      tag: 'quanzi-notification'
    })
    
    notification.onclick = () => {
      window.focus()
      notification.close()
      
      // 处理点击事件
      if (options.onClick) {
        options.onClick()
      }
    }
    
    // 自动关闭
    setTimeout(() => {
      notification.close()
    }, 5000)
  }
  // #endif
  
  // #ifdef APP-PLUS
  plus.push.createMessage(content, 'UNI_MESSAGE', {
    title: title,
    icon: icon,
    sound: sound,
    vibrate: vibrate
  })
  // #endif
}

// 处理推送消息点击
const handlePushClick = (message) => {
  const { payload } = message
  
  try {
    const data = JSON.parse(payload)
    
    switch (data.type) {
      case 'post_like':
        // 跳转到帖子详情
        uni.navigateTo({
          url: `/pages/post/detail?id=${data.postId}`
        })
        break
        
      case 'post_comment':
        // 跳转到帖子详情
        uni.navigateTo({
          url: `/pages/post/detail?id=${data.postId}`
        })
        break
        
      case 'follow':
        // 跳转到用户主页
        uni.navigateTo({
          url: `/pages/user/profile?id=${data.userId}`
        })
        break
        
      case 'topic_invite':
        // 跳转到圈子详情
        uni.navigateTo({
          url: `/pages/circles/detail?id=${data.topicId}`
        })
        break
        
      default:
        // 跳转到消息页面
        uni.switchTab({
          url: '/pages/message'
        })
    }
  } catch (error) {
    console.error('处理推送点击失败:', error)
  }
}

// 处理推送消息接收
const handlePushReceive = (message) => {
  const { title, content, payload } = message
  
  // 保存到本地消息列表
  saveLocalMessage({
    title,
    content,
    payload,
    timestamp: Date.now(),
    read: false
  })
  
  // 更新消息角标
  updateMessageBadge()
  
  // 触发自定义事件
  uni.$emit('pushMessageReceived', message)
}

// 保存本地消息
const saveLocalMessage = (message) => {
  let messages = storage.getStorageSync('localMessages') || []
  messages.unshift(message)
  
  // 限制消息数量
  if (messages.length > 100) {
    messages = messages.slice(0, 100)
  }
  
  storage.setStorageSync('localMessages', messages)
}

// 获取本地消息
export const getLocalMessages = () => {
  return storage.getStorageSync('localMessages') || []
}

// 标记消息为已读
export const markMessageAsRead = (messageId) => {
  let messages = getLocalMessages()
  const message = messages.find(m => m.id === messageId)
  if (message) {
    message.read = true
    storage.setStorageSync('localMessages', messages)
    updateMessageBadge()
  }
}

// 清除所有本地消息
export const clearLocalMessages = () => {
  storage.removeStorageSync('localMessages')
  updateMessageBadge()
}

// 更新消息角标
export const updateMessageBadge = () => {
  const messages = getLocalMessages()
  const unreadCount = messages.filter(m => !m.read).length
  
  // #ifdef MP-WEIXIN
  if (unreadCount > 0) {
    uni.setTabBarBadge({
      index: 3, // 消息tab的索引
      text: unreadCount > 99 ? '99+' : unreadCount.toString()
    })
  } else {
    uni.removeTabBarBadge({
      index: 3
    })
  }
  // #endif
  
  // #ifdef H5
  // H5环境更新页面标题
  if (unreadCount > 0) {
    document.title = `(${unreadCount}) 圈子社交`
  } else {
    document.title = '圈子社交'
  }
  // #endif
  
  // #ifdef APP-PLUS
  if (unreadCount > 0) {
    plus.runtime.setBadgeNumber(unreadCount)
  } else {
    plus.runtime.setBadgeNumber(0)
  }
  // #endif
}

// 获取未读消息数量
export const getUnreadMessageCount = () => {
  const messages = getLocalMessages()
  return messages.filter(m => !m.read).length
}

// 订阅特定类型的通知
export const subscribeNotification = (type) => {
  const settings = storage.settingsStorage.getSettings()
  
  // #ifdef MP-WEIXIN
  // 微信小程序订阅消息
  const templateIds = {
    'post_like': 'template_like_id',
    'post_comment': 'template_comment_id',
    'follow': 'template_follow_id',
    'topic_invite': 'template_invite_id'
  }
  
  const templateId = templateIds[type]
  if (templateId) {
    uni.requestSubscribeMessage({
      tmplIds: [templateId],
      success: (res) => {
        if (res[templateId] === 'accept') {
          settings.notifications = settings.notifications || {}
          settings.notifications[type] = true
          storage.settingsStorage.setSettings(settings)
        }
      }
    })
  }
  // #endif
  
  // #ifdef H5 || APP-PLUS
  // H5和APP环境直接保存设置
  settings.notifications = settings.notifications || {}
  settings.notifications[type] = true
  storage.settingsStorage.setSettings(settings)
  // #endif
}

// 取消订阅通知
export const unsubscribeNotification = (type) => {
  const settings = storage.settingsStorage.getSettings()
  settings.notifications = settings.notifications || {}
  settings.notifications[type] = false
  storage.settingsStorage.setSettings(settings)
}

// 检查通知权限
export const checkNotificationPermission = () => {
  return new Promise((resolve) => {
    // #ifdef MP-WEIXIN
    // 微信小程序检查订阅消息设置
    uni.getSetting({
      withSubscriptions: true,
      success: (res) => {
        resolve({
          authorized: true,
          subscriptions: res.subscriptionsSetting || {}
        })
      },
      fail: () => {
        resolve({ authorized: false })
      }
    })
    // #endif
    
    // #ifdef H5
    if ('Notification' in window) {
      resolve({
        authorized: Notification.permission === 'granted',
        permission: Notification.permission
      })
    } else {
      resolve({ authorized: false, supported: false })
    }
    // #endif
    
    // #ifdef APP-PLUS
    // APP环境检查推送权限
    resolve({ authorized: true })
    // #endif
  })
}

// 打开通知设置
export const openNotificationSettings = () => {
  // #ifdef MP-WEIXIN
  uni.openSetting({
    withSubscriptions: true
  })
  // #endif
  
  // #ifdef H5
  uni.showModal({
    title: '提示',
    content: '请在浏览器设置中允许通知权限',
    showCancel: false
  })
  // #endif
  
  // #ifdef APP-PLUS
  plus.runtime.openURL('app-settings:')
  // #endif
}

// 发送测试通知
export const sendTestNotification = () => {
  sendLocalNotification({
    title: '测试通知',
    content: '这是一条测试通知消息',
    onClick: () => {
      uni.showToast({
        title: '通知点击成功',
        icon: 'success'
      })
    }
  })
}

export default {
  initPush,
  sendLocalNotification,
  getLocalMessages,
  markMessageAsRead,
  clearLocalMessages,
  updateMessageBadge,
  getUnreadMessageCount,
  subscribeNotification,
  unsubscribeNotification,
  checkNotificationPermission,
  openNotificationSettings,
  sendTestNotification
}